module.exports = {
    initialization: initialization
};

var mysql = require('mysql'); //调用MySQL模块
//创建一个connection
var client = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '',
    port: '3306',
    database: 'mschool',
    charset: 'UTF8_GENERAL_CI',
    debug: false
});
client.config.queryFormat = function(query, values) {
    if (!values) return query;
    return query.replace(/\:(\w+)/g, function(txt, key) {
        if (values.hasOwnProperty(key)) {
            return this.escape(values[key]);
        }
        return txt;
    }.bind(this));
};


function initialization(callback) {
    console.log('initialization sql');

    //创建一个connection
    client.connect(function(err) {
        if (err) {
            console.log('*sql:[query] - :' + err);
            return;
        }
        console.log('*sql:[connection connect] succeed!');

        var dbObj = {};
        dbObj.User = require('./object/user.js')(client);
        dbObj.Item = require('./object/item.js')(client);
        dbObj.Category = require('./object/category.js')(client);
        callback(dbObj);
    });
}

global.sql_check = function(data) {
    if(typeof data === 'object'){
        for(var i in data){
            if(global.sql_check(data[i])){
                return true;
            }
        }
        return false;
    }
    if(typeof data === 'string'){
        var reg = /^\?(.*)(select%20|insert%20|delete%20from%20|count\(|drop%20table|update%20truncate%20|asc\(|mid\(|char\(|xp_cmdshell|exec%20master|net%20localgroup%20administrators|\"|:|net%20user|\|%20or%20)(.*)$/gi;
        if (reg.test(data)) {
            return true;
        }
    }

    return false;
};